import {
  Controller,
  Get,
  HttpException,
  HttpStatus,
  Query,
} from '@nestjs/common';
import { EmailService } from './email.service';
import { RedisService } from 'src/redis/redis.service';

@Controller('email')
export class EmailController {
  constructor(
    private readonly emailService: EmailService,
    private readonly redisService: RedisService,
  ) {}

  @Get('send')
  async sendEmail(@Query('email') email: string) {
    console.log('email');
    try {
      const emailCode = await this.redisService.get(email);

      if (emailCode) {
        throw new HttpException('验证码已发送', HttpStatus.BAD_REQUEST);
      }

      const code = Math.random().toString().slice(2, 6);
      await this.redisService.set(email, code, 60);
      await this.emailService.sendeEmail({
        to: email,
        subject: '验证码',
        html: `<h1>${code}</h1>`,
      });
      return { msg: '发送成功' };
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
    }
  }
}
